<?php
namespace App\Services\WxCard\MemberCard;

use App\Models\WxCardMemberGive;
use App\Models\WxCardMemberList;
use App\Services\EasyWechat;
use App\Services\WxCardMemberLevelService;
use App\Services\WxErrorService;
use App\Services\WxMaterial\WxMaterialNews;

/**
 * 通用会员类会员卡卡业务逻辑
 * @package App\Services\WxCard\MemberCard
 */
class CommonCard extends MemberCardAbstract
{
    /**
     * 更新会员卡数据
     * @param $memberListId 会员对应该会员卡的自增ID
     * @return bool
     * @throws \Exception
     */
    public function updateUserCardData($memberListId)
    {
        //提交接口更新数据
        $apiPostData = [];

        \DB::beginTransaction();
        try {
            $memberListModel = WxCardMemberList::findOrFail($memberListId);
            $apiPostData['card_id'] = $memberListModel->card_id;
            $apiPostData['code'] = $memberListModel->user_card_code;
            //会员等级
            $levelData = (new WxCardMemberLevelService())->checkValid($memberListModel->card_base_id, $memberListModel->openid);
            //会员卡数据更新
            if ($levelData){
                $memberListModel->level_id = $levelData['id'];
                $memberListModel->level_key = $levelData['key'];
                $memberListModel->level_name = $levelData['name'];
            }
            //等级奖励发放
            if (!empty($levelData)){
                $memberGiveModel = WxCardMemberGive::where('openid', $memberListModel->openid)->where('card_base_id', $memberListModel->card_base_id)->where('level_key', $levelData['key'])->first();
                if (empty($memberGiveModel)){
                    $memberGiveModel = new WxCardMemberGive;
                    $memberGiveModel->openid = $memberListModel->openid;
                    $memberGiveModel->card_base_id = $memberListModel->card_base_id;
                    $memberGiveModel->level_key = $levelData['key'];
                }
                //【积分奖励】
                $giveBonus = !empty($memberGiveModel->give_bonus) ? $memberGiveModel->give_bonus : ['status'=>'no_send','remark'=>'未发送'];
                empty($memberGiveModel) && $memberGiveModel->give_bonus = ['status'=>'none'];
                if (!empty($levelData['give_bonus']) && $levelData['give_bonus'] > 0){
                    //未奖励过才奖励
                    if ($giveBonus['status'] != 'send_success'){
                        $scorePrizeParams = [
                            'openid'=>$memberListModel->openid,'key_type'=>'card_member','score'=>$levelData['give_bonus'],'remark'=>'会员升级【'.$levelData['name'].'】积分奖励','key_id'=>$memberListId
                        ];
                        try{
                            $logId = (new \App\Services\Api\SogalBaseScoreService())->addScore($scorePrizeParams);
                            $giveBonus['status'] = 'send_success';
                            $giveBonus['score_log_id'] = $logId;
                            $giveBonus['remark'] = '奖励积分成功';

                            //传给接口的本次积分变动值
                            $apiPostData['add_bonus'] = (int) $levelData['give_bonus'];
                        }catch (\Exception $e){
                            $giveBonus['status'] = 'send_fail';
                            $giveBonus['remark'] = '奖励积分失败：'. $e->getMessage();
                            \Log::error($e->getMessage(), ['scorePrizeParams' => $scorePrizeParams]);
                        }
                    }
                }else{
                    $giveBonus['status'] = 'no_prize';
                    $giveBonus['remark'] = '未设置积分奖励';
                }
                $memberGiveModel->give_bonus = $giveBonus;
                //【优惠券奖励】
                $giveCoupon = !empty($memberGiveModel->give_coupon) ? $memberGiveModel->give_coupon : ['status'=>'no_send','remark'=>'未发送'];
                if (!empty($levelData['give_bonus'])){
                    $giveCoupon['status'] = 'no_open';
                    $giveCoupon['remark'] = '未开放优惠券奖励';
                    //未奖励过才奖励
                    if ($giveBonus['status'] != 'send_success'){

                    }
                }else{
                    $giveCoupon['status'] = 'no_prize';
                    $giveCoupon['remark'] = '未设置优惠券奖励';
                }
                $memberGiveModel->give_coupon = $giveCoupon;
                $memberGiveModel->save();

                //会员总积分数据
                $sfyScoreModel = \App\ModelsSogalBase\SfyScore::where('openid', $memberListModel->openid)->first();
                if (!empty($sfyScoreModel->sum_score)){
                    $apiPostData['bonus'] = $sfyScoreModel->sum_score;
                    $apiPostData['notify_optional']['is_notify_bonus'] = true;
                    //更新积分数
                    $memberListModel->bonus = $sfyScoreModel->sum_score;
                }
                $memberListModel->save();
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        //用户会员卡数据
        $memberModel = \App\Models\WxCardMember::where('card_base_id', $memberListModel->card_base_id ?? 0)->first();
        //会员卡数据
        $memberData = $memberModel ? $memberModel->toArray() : [];

        //更新会员等级数据
        $levelFieldPosition = '';
        if ($memberData) {
            //重要自定义会员信息一
            if ($memberData['custom_field1']['isopen']) {
                if ($memberData['custom_field1']['name_type'] == 'FIELD_NAME_TYPE_LEVEL' || (empty($memberData['custom_field1']['name_type']) && in_array($memberData['custom_field1']['name'], ['会员等级']))) {
                    $levelFieldPosition = 1;
                }
            }
            //重要自定义会员信息二
            if ($memberData['custom_field2']['isopen']) {
                if ($memberData['custom_field2']['name_type'] == 'FIELD_NAME_TYPE_LEVEL' || (empty($memberData['custom_field2']['name_type']) && in_array($memberData['custom_field2']['name'], ['会员等级']))) {
                    $levelFieldPosition = 2;
                }
            }
            //重要自定义会员信息三
            if ($memberData['custom_field3']['isopen']) {
                if ($memberData['custom_field3']['name_type'] == 'FIELD_NAME_TYPE_LEVEL' || (empty($memberData['custom_field3']['name_type']) && in_array($apiPostData['custom_field3']['name'], ['会员等级']))) {
                    $levelFieldPosition = 3;
                }
            }
        }
        //存在会员等级字段则更新对应栏目数据
        if (!empty($levelFieldPosition)){
            if ($levelData){
                $apiPostData['background_pic_url'] = $levelData['background_pic_url'];
                $apiPostData['custom_field_value'.$levelFieldPosition] = $levelData['name'];
                $apiPostData['notify_optional']['is_notify_custom_field'.$levelFieldPosition] = true;
            }else{
                if (!empty($memberData['background_pic_url'])) {
                    $apiPostData['background_pic_url'] = (new WxMaterialNews())->getWxViewUrl($memberData['background_pic_url']);
                }else{
                    $apiPostData['background_pic_url'] = '';
                }
                $apiPostData['custom_field_value'.$levelFieldPosition] = '';
                $apiPostData['notify_optional']['is_notify_custom_field'.$levelFieldPosition] = true;
            }
        }
        \Log::info('刷新用户会员卡数据', $apiPostData);
        $app = EasyWechat::officialAccount();
        $apiRs = $app->card->member_card->updateUser($apiPostData);
        WxErrorService::checkApiResponse($apiRs);
        return true;
    }
}